import random
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from login_register import constant
from login_register.serializers import UserRegisterSerializer


class UserRegisterView(CreateAPIView):
    serializer_class = UserRegisterSerializer




class SmsCodeView(APIView):
    def get(self, request, mobile):
        '''
        # 判断该手机号是否在发送间隔内
        # 生成短信验证码,发送短信验证码
        # 存入Redis缓存 设置有效期
        # 返回结果
        '''
        # 获取redis链接
        redis_conn = get_redis_connection('sms_code')
        # 判断该手机号是否在发送间隔内
        ret = redis_conn.get('sms_code_flag_{}'.format(mobile))
        if ret is not None:
            return Response({'success': False, 'message': '请求次数过于频繁'}, status=status.HTTP_400_BAD_REQUEST)
            # 生成短信验证码
        sms_code = random.randint(100000, 999999)
        print(sms_code)
        # 建立管道
        pipeline = redis_conn.pipeline()
        pipeline.setex('sms_code_{}'.format(mobile), constant.SMS_CODE_EXPIRATION_TIME, sms_code)  # 设置有效期
        pipeline.setex('sms_code_flag_{}'.format(mobile), constant.SEND_SMS_CODE_INTERVAL, 1)  # 设置发送间隔
        pipeline.execute()
        return Response({'success': True, 'message': 'OK', 'sms_code':sms_code})



